package com.myx.typhoon.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.myx.typhoon.business.domain.User;
import com.myx.typhoon.common.enums.LoginStatus;
import com.myx.typhoon.sys.service.UserService;
import com.myx.typhoon.web.form.LoginForm;
import com.myx.typhoon.web.security.SecurityUtil;

/**  
 * @author myx
 * @createTime 2016年1月7日 上午10:44:36  
 * 
 */
@Controller
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Resource
	private UserService userService;
	
	@Resource
	private HttpServletRequest request;
	
	/**
	 * 请求到登录页
	 * @param msg
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login",method = RequestMethod.GET)
	public String login(@ModelAttribute("msg") String msg, Model model) {
		model.addAttribute("msg", msg);
		HttpSession session = request.getSession();
		session.setAttribute("return_url", request.getHeader("referer"));
		return "portal/signin";
	}
	
	/**
	 * 登录请求
	 * @param user
	 * @param result
	 * @param model
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@ModelAttribute("loginForm") @Valid LoginForm user, BindingResult result,
			Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		if(result.hasErrors()) {
			logger.error("login validate fail!");
			return "redirect:/login";
		}
		try {
			LoginStatus status = SecurityUtil.loginToken(user);
			if(status.getStatus() == 200) {
				//记录上词请求地址
				String return_url = (String) request.getSession().getAttribute("return_url");
				if(return_url != null && !return_url.contains("/login")) {
					return "redirect:"+return_url;
				}
				return "redirect:/index";
			}
			redirectAttributes.addFlashAttribute("msg", status.getMessage());
		} catch (Exception e) {
			logger.error("login",e);
		}
		return "redirect:/login";
	}
	
	/**
	 * 请求到注册页
	 * @return
	 */
	@RequestMapping(value = "/regist")
	public String regist() {
		return "portal/signup";
	}
	
	@RequestMapping(value = "/regist",method = RequestMethod.POST)
	public String regist(@ModelAttribute("user") User user) {
		int count = userService.saveUser(user);
		if(count >0) {
			LoginForm loginUser = new LoginForm();
			loginUser.setUsername(user.getUsername());
			loginUser.setPassword(user.getPassword());
			LoginStatus status = SecurityUtil.loginToken(loginUser);
			if(status.getStatus() == 200) {
				//System.out.println(request.getHeader("referer"));
				return "redirect:/index";
			}
		}
		return "redirect:/login";
	}
	
	/**
	 * 检查用户名是否已存在
	 * @param username
	 * @return
	 */
	@RequestMapping("/checkUsername")
	public @ResponseBody Boolean checkUsername(@RequestParam("username") String username) {
		User user = userService.findUserByUserName(username);
		if(user != null) {
			return false;
		}
		return true;
	}
	
	/**
	 * 检查邮箱是否已存在
	 * @param email
	 * @return
	 */
	@RequestMapping("/checkEmail")
	public @ResponseBody Boolean checkEmail(@RequestParam("email") String email) {
		User user = userService.findUserByEmail(email);
		if(user != null) {
			return false;
		}
		return true;
	}
	
	/**
	 * 检查验证码是否正确
	 * @return
	 */
	@RequestMapping("/checkCaptcha")
	public @ResponseBody Boolean checkCaptcha(@RequestParam("captcha") String captcha) {
		//TODO 校验验证码 
		return true;
	}
	
	/**
	 * 退出登录
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout() {
		SecurityUtil.logutToken();
		return "redirect:/index";
	}
}
